<?php

namespace app\admin\controller;

use think\Lang;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class Ziwork extends AdminControl
{

    const EXPORT_SIZE = 1000;

    public function _initialize()
    {
        parent::_initialize();
        Lang::load(APP_PATH . 'admin/lang/' . config('default_lang') . '/ziwork.lang.php');
        Lang::load(APP_PATH . 'admin/lang/' . config('default_lang') . '/admin.lang.php');
    }

    /**
     * 子客服客服管理
     */
    public function index()
    {
        $model = model('ziwork');
        $condition = [];
        /**
         * 检索条件
         */
        $sanjiArr = [];
        if (!empty(input('param.search_name'))) {
            $condition['ds_work_zi.name'] = array('like', "%" . input('param.search_name') . "%");
        }
        if (!empty(input('param.search_truename'))) {
            $condition['ds_work_zi.truename'] = array('like', "%" . input('param.search_truename') . "%");
        }
        if (!empty(input('param.typeid'))) {
            $condition['ds_work_zi.typeid'] = input('param.typeid');
        }
        if (!empty(input('param.province_id'))) {
            $arr = explode(' ', input('param.areainfo'));

            if (count($arr) == 1) {
                $condition['ds_work_zi.provinceinfo'] = array('like', "%" . $arr[0] . "%");
            } elseif (count($arr) == 2) {
                $areamod = model('area');
                $yiji = $areamod->getAreaInfo(['area_name' => $arr[0]], 'area_id');
                $erji = $areamod->getAreaInfo(['area_name' => $arr[1], 'area_parent_id' => $yiji['area_id']], 'area_id');
                $sanjiArr = $areamod->getChildrenIDs($erji['area_id']);
            } elseif (count($arr) == 3) {
                $areamod = model('area');
                $yiji = $areamod->getAreaInfo(['area_name' => $arr[0]], 'area_id');
                $erji = $areamod->getAreaInfo(['area_name' => $arr[1], 'area_parent_id' => $yiji['area_id']], 'area_id');
                $sanji = $areamod->getAreaInfo(['area_name' => $arr[2], 'area_parent_id' => $erji['area_id']], 'area_id');
                $condition['ds_work_zi.area_id'] = array('like', "%," . $sanji['area_id'] . ",%");
            }
        }
        $worktype = model('worktype');
        $typeaArr = $worktype->getWorktypeList(['status' => 1], 'id,name');
        $list = $model->getList($condition, "ds_work_zi.*,w.name AS typename", 10, $sanjiArr);
        $this->assign('showpage', $model->page_info->render());
        $this->assign('list', $list);
        $this->assign('search_name', trim(input('param.search_name')));
        $this->assign('search_truename', trim(input('param.search_truename')));
        $this->assign('typeaArr', $typeaArr);
        $this->assign('typeid', input('param.typeid'));
        $this->assign('province_id', input('param.province_id'));
        $this->assign('city_id', input('param.city_id'));
        $this->assign('area_id', input('param.area_id'));
        $this->assign('areainfo', input('param.areainfo'));
        $this->setAdminCurItem('index');
        #获取当前客服的登录信息
        $kefu_info = db('work_zi')->where(['id' => session('admin_id')])->find();
        $this->assign('j_info', json_encode($kefu_info));
        return $this->fetch();
    }

    /**
     * 增加子客服
     */
    public function add()
    {
        $model = model('ziwork');
        if (request()->isPost()) {
            // $validate = validate('ziwork');
            // if (!$validate->scene('add')->check($_POST)) {
            //     $this->error($validate->getError());
            // }

            #生成极光账号
            $post = [
                'username' => $_POST['account'],
                'password' => $_POST['password'],
                'nickname' => $_POST['name'],
                'avatar' => '',
                'signature' => ''
            ];
            $J_name = JmRegist($post);
            $J_info = json_decode($J_name, true);

            $_POST['zi_j_name'] = $J_info[0]['username'];

            unset($_POST['queren_password']);
            if (!empty($_POST['store_work'])) {
                $_POST['store_typeid'] = $_POST['store_work'];
            } else {
                $_POST['store_typeid'] = 0;
            }
            unset($_POST['store_work']);
            $_POST['password'] = md5($_POST['password']);
            $_POST['login_num'] = 0;
            $_POST['admin_id'] = session('admin_id');
            $_POST['admin_name'] = session('admin_name');
            $_POST['created_at'] = $_POST['updated_at'] = date('Y-m-d H:i:s', time());
            if ($model->add($_POST)) {
                $this->log(lang('ds_add') . lang('ziwork_index_title') . '[' . input('post.name') . ']', 1);
                dsLayerOpenSuccess(lang('ds_common_save_succ'));
            } else {
                $this->error(lang('ds_common_save_fail'));
            }
        } else {
            $mod = model('worktype');
            $arr = [
                'id' => '',
                'typeid' => '',
                'name' => '',
                'account' => '',
                'password' => '',
                'userids' => '',
                'status' => 1,
                'province_id' => '',
                'city_id' => '',
                'area_id' => '',
                'areainfo' => '',
                'truename' => '',
                'idcard' => '',
                'sex' => 0,
            ];
            $typeaArr = $mod->getWorktypeList(['status' => 1], 'id,name');

            $smod = model('storework');
            $store_work = $smod->getStoreWorkInfo();

            $this->assign('array', $arr);
            $this->assign('typeaArr', $typeaArr);
            $this->assign('store_work', $store_work);
            return $this->fetch('form');
        }
    }

    /**
     * 修改子客服
     */
    public function edit()
    {
        $model = model('ziwork');
        if (request()->isPost()) {
            // $validate = validate('ziwork');
            // if (!$validate->scene('edit')->check($_POST)) {
            //     $this->error($validate->getError());
            // }
            $_POST['updated_at'] = date('Y-m-d H:i:s', time());
            if (strlen($_POST['password'])) {
                $_POST['password'] = md5($_POST['password']);
            } else {
                unset($_POST['password']);
            }
            unset($_POST['queren_password']);
            if (!empty($_POST['store_work'])) {
                $_POST['store_typeid'] = $_POST['store_work'];
            } else {
                $_POST['store_typeid'] = 0;
            }
            unset($_POST['store_work']);
            $detail = $model->getInfo(['id' => input('get.workid')], 'area_id');
            if ($detail['area_id'] != input('post.area_id')) {
                $_POST['userids'] = '';
            }
            $res = $model->edit(['id' => input('post.id')], $_POST);
            if ($res) {
                $this->log(lang('ds_update') . lang('ziwork_index_title') . '[' . input('post.name') . ']', 1);
                dsLayerOpenSuccess(lang('ds_common_save_succ'));
            } else {
                $this->log(lang('ds_update') . lang('ziwork_index_title') . '[' . input('post.name') . ']', 0);
                $this->error(lang('ds_common_save_fail'));
            }
        } else {
            $worktypemod = model('worktype');
            $typeaArr = $worktypemod->getWorktypeList(['status' => 1], 'id,name');
            $res = $model->getInfo(['id' => input('get.workid')]);
            $smod = model('storework');
            $store_work = $smod->getStoreWorkInfo();
            $this->assign('array', $res);
            $this->assign('typeaArr', $typeaArr);
            $this->assign('store_work', $store_work);
            return $this->fetch('edit');
        }
    }

    /**
     * 根据areaid分配用户
     */
    public function fenpei()
    {
        $model = model('ziwork');
        $condition = [];
        /**
         * 根据当前分类,
         */

        /**
         * 检索条件
         */
        if (!empty(input('param.search_name'))) {
            $condition['member_name'] = array('like', "%" . input('param.search_name') . "%");
        }
        if (!empty(input('param.search_phone'))) {
            //???
            $condition['member_name'] = array('like', input('param.search_phone') . "%");
        }
        if (!empty(input('param.province_id'))) {
            $condition['member_provinceid'] = input('param.province_id');
        }
        if (!empty(input('param.city_id'))) {
            $condition['member_cityid'] = input('param.city_id');
        }
        if (!empty(input('param.area_id'))) {
            $condition['member_areaid'] = input('param.area_id');
        }
        if (!empty(input('param.areainfo'))) {
            $condition['member_areainfo'] = array('like', input('param.areainfo') . "%");
        }

        $ziworkDetail = $model->getInfo(['id' => input('param.workid')]);
        /**
         * 获取当前分类下,已经分配给其他用户的
         */
        $useridArr = $model->getList(['typeid' => input('param.typeid'), 'id' => ['neq', input('param.workid')]], 'userids');
        $useridStr = ''; ##用于存储已经分配过的用户id
        foreach ($useridArr as $v) {
            if ($v['userids']) {
                if ($useridStr) {
                    $useridStr = $useridStr . ',' . $v['userids'];
                } else {
                    $useridStr = $useridStr . $v['userids'];
                }
            }
        }
        if (!empty(input('param.status_search'))) {
            if (input('param.status_search') == 1) {
                $condition['member_id'] = array('in', $ziworkDetail['userids']);
            } elseif (input('param.status_search') == 2) {
                $condition['member_id'] = array('in', explode(',', $useridStr));
            } elseif (input('param.status_search') == 3) {
                //                '暂未分配';
                $idArr = array_merge(explode(',', $useridStr), explode(',', $ziworkDetail['userids']));
                $condition['member_id'] = array('not in', $idArr);
            }
        }

        $model = model('member');
        $list = $model->getMemberList($condition, 'member_id,member_name,member_mobile,member_areainfo,member_truename', 10);
        $this->assign('showpage', $model->page_info->render());
        $this->assign('list', $list);
        $this->assign('ziworkDetail', $ziworkDetail);
        $this->assign('search_name', trim(input('param.search_name')));
        $this->assign('search_phone', trim(input('param.search_phone')));
        //        var_dump(input('param.province_id'));
        $this->assign('province_id', input('param.province_id'));
        $this->assign('city_id', input('param.city_id'));
        $this->assign('area_id', input('param.area_id'));
        $this->assign('areainfo', input('param.areainfo'));
        $this->assign('status_search', trim(input('param.status_search')));
        $this->assign('useridStr', $useridStr);
        $this->assign('workid', input('param.workid'));
        $this->assign('typeid', input('param.typeid'));
        $this->setAdminCurItem('index');
        return $this->fetch();
    }

    /**
     * 删除子客服
     */
    public function del()
    {
        $model = model('ziwork');
        $storeworkid = input('param.workid');
        $storeworkidArr = ds_delete_param($storeworkid);
        if ($storeworkidArr == FALSE) {
            $this->log(lang('ds_del') . lang('ziwork_index_title') . '[ID:' . $storeworkid . ']', 0);
            ds_json_encode(10001, lang('param_error'));
        }
        $model->del(array('id' => array('in', implode(',', $storeworkidArr))));
        $this->log(lang('ds_del') . lang('ziwork_index_title') . '[ID:' . $storeworkid . ']', 1);
        ds_json_encode(10000, lang('ds_common_del_succ'));
    }

    /**
     * ajax
     */
    public function ajax()
    {
        $model = model('ziwork');
        switch (input('get.branch')) {
            case 'check_work_name':
                $condition['name'] = input('get.workname');
                $condition['id'] = ['neq', input('get.workid')];
                $info = $model->getInfo($condition);
                if ($info) {
                    exit('false');
                } else {
                    exit('true');
                }
            case 'check_work_account':
                $condition['account'] = input('get.workaccount');
                $condition['id'] = ['neq', input('get.workid')];
                $info = $model->getInfo($condition);
                $zhuwork_model = model('zhuwork');
                $info2 = $zhuwork_model->checkName($condition, 'id');
                if ($info || $info2) {
                    exit('false');
                } else {
                    exit('true');
                }
                //            case 'edit_status':
                //                $condition['id']= input('param.id');
                //                $data[input('param.column')] = input('param.value');
                //                $model->edit($condition,$data);
                //                $this->log(lang('ds_edit') . lang('ziwork_index_title') . '[ID:' . intval(input('param.id')) . ')', 1);
                //                echo  'true';
                //                exit;
                //                break;
        }
    }

    public function edit_status()
    {
        $model = model('ziwork');
        $condition['id'] = input('param.id');
        $data[input('param.column')] = input('param.value');
        $model->edit($condition, $data);
        $this->log(lang('ds_edit') . lang('ziwork_index_title') . '[ID:' . intval(input('param.id')) . ')', 1);
        ds_json_encode(10000, lang('ds_common_op_succ'));
    }
    public function fenquyu()
    {
        $model = model('ziwork');
        $workid = input('param.workid');
        $data =  $model->getInfo(['id' => $workid]);
        $top_area = db('area')->where(['area_deep' => 1, 'area_parent_id' => 0])->select();
        foreach ($top_area as $k => $v) {
            $top_area[$k]['area_list'] = db('area')->where(['area_deep' => 2, 'area_parent_id' => $v['area_id']])->field('area_id')->select();
            if (empty($top_area[$k]['area_list'])) {
                $top_area[$k]['area_list'][] = ['area_id' => $v['area_id']];
            }
        }
        foreach ($top_area as $k => $v) {
            if (empty($v['area_list'])) {
                $top_area[$k]['last_id'][] = [['area_id' => $v['area_id']]];
            } else {
                foreach ($v['area_list'] as $ke => $va) {
                    $top_area[$k]['last_id'][] = $res = db('area')->where(['area_deep' => 3, 'area_parent_id' => $va['area_id']])->field('area_id')->select();
                }
            }
        }
        foreach ($top_area as $k => $v) {
            foreach ($v['last_id'] as $ke => $va) {
                foreach ($va as $key => $val) {
                    $top_area[$k]['last_id_info'][] = $val['area_id'];
                }
            }
            if (!isset($top_area[$k]['last_id_info'])) {
                foreach ($v['area_list'] as $ke => $va) {
                    foreach ($va as $key => $val) {
                        $top_area[$k]['last_id_info'][] = $val;
                    }
                }
            }
            unset($top_area[$k]['last_id']);
            unset($top_area[$k]['area_list']);
        }
        foreach ($top_area as $k => $v) {
            if (isset($v['last_id_info'])) {
                $top_area[$k]['last_ids'] = implode(',', $v['last_id_info']);
            } else {
                $top_area[$k]['last_ids'] = $v['area_id'];
            }
        }
        $this->assign('top_area', $top_area);
        $this->assign('workid', $workid);
        $this->assign('detail', $data);
        return $this->fetch('fenquyu');
    }

    /**
     * 获取卖家栏目列表,针对控制器下的栏目
     */
    protected function getAdminItemList()
    {
        $menu_array = array(
            array(
                'name' => 'index',
                'text' => lang('ds_manage'),
                'url' => url('Ziwork/index'),
            ),
            array(
                'name' => 'add',
                'text' => lang('ds_add'),
                'url' => "javascript:dsLayerOpen('" . url('Ziwork/add') . "','" . lang('ds_add') . "')"
            ),
        );
        return $menu_array;
    }
    /**
     * ajax 获取城市
     */
    public function ajax_area()
    {
        $choose_id = input('choose_id');
        $area_list = db('area')->where(['area_parent_id' => $choose_id])->select();

        foreach ($area_list as $k => $v) {
            $area_list[$k]['area_list'] = db('area')->where(['area_deep' => 3, 'area_parent_id' => $v['area_id']])->field('area_id')->select();
        }

        foreach ($area_list as $k => $v) {
            foreach ($v['area_list'] as $ke => $va) {
                $area_list[$k]['last_id_info'][] = $va['area_id'];
            }
            unset($area_list[$k]['area_list']);
        }

        foreach ($area_list as $k => $v) {
            if (isset($v['last_id_info'])) {
                $area_list[$k]['last_ids'] = implode(',', $v['last_id_info']);
            } else {
                $area_list[$k]['last_ids'] = $v['area_id'];
            }
        }
        $area_info = db('area')->where(['area_id' => $choose_id])->find();
        if ($area_info['area_parent_id'] == 0) {

            foreach ($area_list as $k => $v) {
                if (isset($v['last_id_info'])) {
                    $area_list[$k]['last_ids'] = implode(',', $v['last_id_info']);
                    $area_list[$k]['top_name'] = $area_info['area_name'];
                } else {
                    $area_list[$k]['last_ids'] = $v['area_id'];
                    $area_list[$k]['top_name'] = $area_info['area_name'];
                }
            }
        } else {
            $area_infos = db('area')->where(['area_id' => $area_info['area_parent_id']])->find();
            foreach ($area_list as $k => $v) {
                if (isset($v['last_id_info'])) {
                    $area_list[$k]['last_ids'] = implode(',', $v['last_id_info']);
                    $area_list[$k]['top_name'] = $area_infos['area_name'];
                } else {
                    $area_list[$k]['last_ids'] = $v['area_id'];
                    $area_list[$k]['top_name'] = $area_infos['area_name'];
                }
            }
        }
        return $area_list;
    }

    public function updateArea()
    {
        $condition['id'] = input('param.workid');
        if (!input('param.area_name/a')) {
            $data['provinceinfo'] = '';
            $data['area_id'] = '';
        } else {
            $data['provinceinfo'] = implode(',', input('param.area_name/a'));
            $data['area_id'] = ',' . implode(',', input('param.area_ids/a')) . ',';
        }
        $model = model('ziwork');
        $res = $model->edit($condition, $data);
        //        if ($res === FALSE)
        //        {
        $this->log(lang('ds_update') . lang('ziwork_index_title') . '[' . input('post.workid') . ']', 1);
        ds_json_encode(0, lang('ds_common_op_succ'));
        //        }else{
        //            $this->log(lang('ds_update') . lang('ziwork_index_title') . '[' . input('post.workid') . ']', 0);
        //            ds_json_encode(10000);
        //        }
    }

    public function savefenpei()
    {
        $memberid = input('param.memberid');
        $model = model('ziwork');
        $workid = input('param.workid');
        if (!$memberid) {
            $this->log('修改' . lang('ziwork_index_title') . '[ID:' . $workid . ']', 0);
            ds_json_encode(10001, '请选择需要设置的会员');
        }
        $res = $model->edit(['id' => $workid], ['userids' => $memberid]);
        $this->log('修改'  . lang('ziwork_index_title') . '[ID:' . $workid . ']', 1);
        //        $this->success( lang('ds_common_save_succ'), 'Ziwork/index');
        ds_json_encode(10000, '设置成功');
    }
}
